package com.chenfy.everysound.util

import android.widget.Toast
import com.chenfy.everysound.base.App
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

fun String.md5(): String {
    try {
        //获取md5加密对象
        val instance: MessageDigest = MessageDigest.getInstance("MD5")
        //对字符串加密，返回字节数组
        val digest:ByteArray = instance.digest(this.toByteArray())
        val sb : StringBuffer = StringBuffer()
        for (b in digest) {
            //获取低八位有效值
            val i :Int = b.toInt() and 0xff
            //将整数转化为16进制
            var hexString = Integer.toHexString(i)
            if (hexString.length < 2) {
                //如果是一位的话，补0
                hexString = "0$hexString"
            }
            sb.append(hexString)
        }
        return sb.toString()

    } catch (e: NoSuchAlgorithmException) {
        e.printStackTrace()
    }

    return ""
}

/**
 * 检查本地文件是否存在
 */
suspend fun checkSound(soundList: List<String>): Boolean = withContext(Dispatchers.IO) {
    val context = App.context
    val fileDir = context.filesDir
    for(soundUrl in soundList){
        val soundFile = File(fileDir,soundUrl)
        if (!soundFile.exists()){
            return@withContext false
        }
    }
    true
}

fun String.toast(){
    Toast.makeText(App.context,this,Toast.LENGTH_SHORT).show()
}